package com.zx.feign.interceptor;

import com.zx.core.utils.AES128CBCNoPadding;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * <p>
 * description: Feign客户端请求加密拦截器 <br>
 * create: 2025-10-12
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@RefreshScope //支持Nacos的动态刷新功能。
@Component
public class FeignEncryptDecryptInterceptor implements RequestInterceptor {

    @Value("${security.encrypt.enabled}")
    private Boolean encryptEnabled;

    @Value("${security.encrypt.key}")
    private String encryptKey;

    @Value("${security.encrypt.iv}")
    private String encryptIv;

    @Override
    public void apply(RequestTemplate template) {
        // 如果未启用加密功能，则直接跳过
        if (!encryptEnabled) {
            return;
        }

        // 检查加密所需的配置是否完整
        if (!StringUtils.hasText(encryptKey) || !StringUtils.hasText(encryptIv)) {
            log.warn("加密配置不完整，跳过加密处理");
            return;
        }

        // 对请求体进行加密
        if (template.body() != null) {
            try {
                String body = new String(template.body());
                // 记录加密前的明文数据
                log.info("Encrypting Feign request body - Plain: {}", body);
                String encryptedBody = AES128CBCNoPadding.encrypt(encryptKey, encryptIv, body);
                // 记录加密后的密文数据
                log.info("Encrypting Feign request body - Encrypted: {}", encryptedBody);
                template.body(encryptedBody);
            } catch (Exception e) {
                log.error("加密Feign请求体失败", e);
            }
        }
    }
}